import os
import shutil
import sys
from sys import exit
import time

# pip install rich
from rich import pretty
from rich import print

pretty.install()

# 定义常量
# BASEFILEDIR = "E:\\Download\\wechart\\WeChat Files\\wxid_mx8l3wt38pm822\\FileStorage\\File\\"
# TARGETFILEDIR = "2024-12"
BASEFILEDIR = "C:\\Users\\Administrator\\Documents\\WeChat Files\\wxid_nk2qkl7hiany22\\FileStorage\\File"
TARGETFILEDIR = "\\2025-04"
FULL_FILE_PATH = BASEFILEDIR + TARGETFILEDIR

# BASEFILEDIR = "E:\\文档\\"
# TARGETFILEDIR = "其他文档"

NEW_FOLDER = "E:\\文档\\"

# AUTHOR_ENUM = ['大树乡谈', '老八付费', '猫哥', '子明', '六爷阿旦付费文', '屠龙手段付费文',
#                '贰掌柜', '唐书院付费文', '米联储见闻', '费曼小茶馆', '鉴茶财', '雪球花甲',
#                '其他文档', '混沌天涯', '安民付费文', '冷眼居中人', '肖磊付费文', '尹香武', '守夜人总司令',
#                '洪灏付费文', '遨游', '岱岱', '付费文', '欧大', '卢克文', '欧神', '毛选', '创始人笔记', '砖瓦厂',
#                '江宁知府', '结构学概论', '咩咩说', '财通', '进阶', '财新', 'others']
# AUTHOR_ENUM_OTHER = ['付费群', '群付费', '付费文']

AUTHOR_ENUM = ['others']
AUTHOR_ENUM_OTHER = []


def init_filedir(author_list):
    for author in author_list:
        if not os.path.exists(NEW_FOLDER + author):
            os.makedirs(NEW_FOLDER + author)


def statistics_on_the_file_types_in_the_folder():
    filelist = {}
    FULL_FILE_PATH = BASEFILEDIR + TARGETFILEDIR

    if not os.path.exists(FULL_FILE_PATH):
        return filelist

    if TARGETFILEDIR not in filelist:
        filelist[TARGETFILEDIR] = {}

    for filename in os.listdir(FULL_FILE_PATH):

        template = filename.split(".")

        if len(template) > 1:
            if template[-1] not in filelist[TARGETFILEDIR]:
                filelist[TARGETFILEDIR][template[-1]] = []
            filelist[TARGETFILEDIR][template[-1]].append(filename)

    return filelist


def file_categorization(filelist):
    all_file_full_path = []
    file_type_list = filelist[TARGETFILEDIR].keys()

    # 创建目标文件夹

    for my_type in file_type_list:
        AUTHOR_ENUM.append(my_type)

    if '1' in AUTHOR_ENUM:
        AUTHOR_ENUM.remove('1')

    if 'pdf' in AUTHOR_ENUM:
        AUTHOR_ENUM.remove('pdf')

    init_filedir(AUTHOR_ENUM)

    for my_type in file_type_list:

        if my_type == 'pdf':
            for document_name in filelist[TARGETFILEDIR][my_type]:
                author_name = "其他文档" + "\\"
                need_step_flag = True

                for aname in AUTHOR_ENUM_OTHER:

                    if aname in document_name:
                        author_name = "付费文" + "\\"
                        need_step_flag = True
                        break

                if need_step_flag:
                    for aname in AUTHOR_ENUM:
                        if aname in document_name:
                            author_name = aname + "\\"
                            break

                document_full_path = NEW_FOLDER + author_name + document_name
                all_file_full_path.append(document_full_path)

        else:
            for document_name in filelist[TARGETFILEDIR][my_type]:

                document_full_path = NEW_FOLDER + my_type + "\\" + document_name
                if my_type == '1':
                    document_full_path = NEW_FOLDER + "others" + "\\" + document_name
                all_file_full_path.append(document_full_path)

    return all_file_full_path


def copy_file_to_new_filedir(all_file_full_path):
    start_time = time.time()
    print("任务开始时间：", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time)))

    file_type_count = {}
    total_file_size = 0
    total_saved_space = 0
    count = 0
    delete_count = 0

    for new_path in all_file_full_path:
        old_path = new_path.split("\\")[-1]

        # 如果文件之前存在，就跳过
        if not os.path.exists(new_path):
            try:
                file_size = os.path.getsize(FULL_FILE_PATH + "\\" + old_path)
                total_file_size += file_size
                shutil.copy2(FULL_FILE_PATH + "\\" + old_path, new_path)

                file_type = new_path.split("\\")[-2]
                if file_type not in file_type_count:
                    file_type_count[file_type] = 0
                file_type_count[file_type] += 1

                count = count + 1
            except IOError as e:
                print("Unable to copy file. %s" % e)
                exit(1)
            except:
                print("Unexpected error:", sys.exc_info())
                exit(1)

        # 如果文件复制成功，删除源文件
        if os.path.exists(new_path):
            try:
                # 获取文件大小
                total_saved_space += os.path.getsize(FULL_FILE_PATH + "\\" + old_path)

                # 删除原文件
                os.remove(FULL_FILE_PATH + "\\" + old_path)

                delete_count = delete_count + 1

            except IOError as e:
                print("Unable to delete file. %s" % e)
                # 继续执行
                # exit(1)
            except:
                print("Unexpected error:", sys.exc_info())
                #继续执行
                # exit(1)

    end_time = time.time()
    print("任务结束时间：", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(end_time)))
    print("任务执行时间：", end_time - start_time, "秒")
    print(f"共分类了 {count} 个文件")
    print(f"共删除了 {delete_count} 个文件")
    print("每种类型的文件处理数量：")
    for file_type, num in file_type_count.items():
        print(f"{file_type}: {num} 个")
    print(f"总共处理的文件大小：{total_file_size / (1024 * 1024):.2f} MB")
    print(f"节省的空间：{total_saved_space / (1024 * 1024):.2f} MB")


# 初始化文件夹
# init_filedir(AUTHOR_ENUM)

# 统计文件夹内文件的文件类型
# ['pdf', 'mp3', 'zip', 'rar', 'exe']
filelist = statistics_on_the_file_types_in_the_folder()
# print(filelist)
# 对列表数量进行判断
if len(filelist) == 0:
    print("没有找到任何文件")
    exit(1)
# 对这个文件夹下面的 文件进行处理，返回文件列表
all_file_full_path = file_categorization(filelist)
copy_file_to_new_filedir(all_file_full_path)
